const express = require("express");
// 创建路由器对象
const r = express.Router();
// 引入第三方连接池模块
const pool = require("../pool/pool");
const md5 = require("md5");
const jwt = require("jsonwebtoken");
const key = "my key";
const nodemailer = require("nodemailer");
const multer = require("multer");
const fs = require("fs");
const moment = require("moment");
const uuid = require("uuid");
const path = require("path");
const Auth = require('../middlewares/Auth')
const { generateToken } = require("../core/utils");
let storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./public/upload");
  },
  filename: function (req, file, cb) {
    let filename = file.originalname;
    let extension = filename
      .substr(filename.lastIndexOf(".") + 1)
      .toLowerCase();
    let dirname = moment().format("Y-MM-DD");
    let mainname = uuid.v1();
    filename = mainname + "." + extension;
    cb(null, filename);
  },
});

const upload = multer({ storage: storage });

//**********************/  //

// 1.注册
r.post("/register", (req, res, next) => {
  let obj = req.body;
  console.log(obj);
  pool.query("INSERT INTO user set ?", [req.body], (err, data) => {
    if (err) {
      next(err);
      return;
    }
    if (data.affectedRows == 1) {
      res.send({ code: 200, msg: "注册成功!" });
    } else {
      res.send({ code: 201, msg: "注册失败!" });
      return;
    }
  });
});
// 2.获取邮箱验证码
r.get("/getcode", (req, res, next) => {
  //在点击发送验证码时 把邮箱和code存入数据库当中
  let code = Math.floor(Math.random() * 900000) + 100000;
  let obj = req.query;
  //  console.log(req.query);
  //  console.log(code);
  console.log(obj.email);
  let sql = `INSERT INTO email_code value ("${obj.email}","${code}")`;
  pool.query(sql, (err, data) => {
    if (err) {
      next(err);
      return;
    }
    console.log(data);
  });
  //简历一个smtp连接
  let transporter = nodemailer.createTransport({
    host: "smtp.163.com",
    secureConnection: true,
    port: 465,
    auth: {
      user: "alili8029@163.com",
      pass: "JYTQLQCKHBLWTJDW",
    },
  });
  //配置相关参数
  let options = {
    from: "alili8029@163.com",
    to: `${obj.email},alili8029@163.com`,
    //邮箱标题
    subject: "SN租车科技有限公司",
    //使用模板字符串书写
    html: `<!DOCTYPE html>
 <html>
 <head>
   <meta charset="UTF-8">
   <title>Document</title>
   <style></style>
 </head>
 <body>
   <div class="center">
     <p>尊敬的用户您好:</p>
     <p>欢迎您注册称为赛男租车行的的注册用户,您的注册验证码是${code}。</p>
   </div>
 </body>
 </html>`,
  };
  transporter.sendMail(options, function (err, msg) {
    if (err) {
      console.log(err);
    } else {
      res.send(msg);
    }
  });
});
// 3.验证检查邮箱是否已经被注册过
r.post("/repeatemail", (req, res, next) => {
  let obj = req.body;
  // console.log(req.body)
  let sql = `SELECT * FROM user WHERE user_email='${obj.user_email}'`;
  // console.log(sql)
  pool.query(sql, (err, data) => {
    if (err) {
      next(err);
      return;
    }
    if (data.length == 0) {
      // 邮箱号没有注册过
      res.send({ code: 200, msg: "邮箱号未被注册" });
    } else {
      res.send({ code: 201, msg: "邮箱号已经被注册" });
    }
  });
});
// 4.验证邮箱验证码 是否正确
r.post("/repeatcode", (req, res, next) => {
  let obj = req.body;
  console.log(obj);
  let sql = `SELECT * FROM email_code WHERE email_code='${obj.code}' `;
  pool.query(sql, (err, data) => {
    if (err) {
      next(err);
      return;
    }
    if (data.length == 0) {
      res.send({ code: 201, msg: "验证码错误" });
    } else {
      res.send({ code: 200, msg: "验证码正确" });
    }
  });
});
// 5.登录
r.post("/login", (req, res, next) => {
  let obj = req.body;

  // console.log(obj)
  let sql = `SELECT * FROM user WHERE user_email=? AND user_pwd=?`;
  // console.log(sql)
  pool.query(sql, [obj.email, obj.pwd], (err, data) => {
    if (err) {
      next(err);
      return;
    }
    console.log(data);
    // console.log(sql)
    if (data.length == 0) {
      // 用户没有注册无法登录
      res.send({ code: 201, msg: "登录失败!请重新登录" });
    } else {
      const token = generateToken(data[0].user_id,2);
      res.send({
        code: 200,
        msg: "登陆成功!",
        token: token,
        user_id: data[0].user_id,
      });
    }
  });
});
// 6.获取用户信息
r.post("/usergetdata", (req, res, next) => {
  let obj = req.body;
  // console.log(obj.Uid)
  let sql = "select * from user where user_id = ?";
  pool.query(sql, [obj.Uid], (err, data) => {
    if (err) {
      next(err);
      return;
    }
    // console.log(data)
    if (data.length !== 0) {
      res.send({ code: 200, data: data });
    }
  });
});
//7.更新手机号
r.post("/updatephone", (req, res, next) => {
  console.log(req.body);
  let obj = req.body;
  let sql = "update user set user_phone = ? where user_id = ?";
  pool.query(sql, [obj.phone, obj.Uid], (err, data) => {
    if (err) {
      next(err);
      return;
    }
    // console.log(data)
    if (data.affectedRows !== 0) {
      let sql01 = "select * from user where user_id =?";
      pool.query(sql01, [obj.Uid], (err, data) => {
        if (err) {
          next(err);
          return;
        }
        // console.log(result)
        res.send({ code: 200, data: data });
      });
    }
  });
});
// 8.更新个人信息
r.post("/updateuser", (req, res, next) => {
  let obj = req.body;
  console.log(obj);
  let sql = "update user set user_cardId = ? ,user_name=? where user_id = ?";
  pool.query(sql, [obj.carid, obj.name, obj.Uid], (err, data) => {
    if (err) {
      next(err);
      return;
    }
    // console.log(data)
    if (data.length !== 0) {
      let sql01 = "select * from user where user_id =?";
      pool.query(sql01, [obj.Uid], (err, data) => {
        if (err) {
          next(err);
          return;
        }
        // console.log(data)
        res.send({ code: 200, data: data });
      });
    }
  });
});
// 9.更新紧急联系人信息
r.post("/updateurgent", (req, res, next) => {
  let obj = req.body;
  console.log(obj);
  let sql =
    "update user set user_urgent_name = ?,user_urgent_phone=? where user_id = ? ";
  pool.query(sql, [obj.urgent_name, obj.urgent_phone, obj.Uid], (err, data) => {
    if (err) {
      next(err);
      return;
    }
    console.log(data);
    if (data.length !== 0) {
      let sql01 = "select * from user where user_id =?";
      pool.query(sql01, [obj.Uid], (err, data) => {
        res.send({ code: 200, data: data });
      });
    }
  });
});

// 浏览自定义存储规则的文件上传操作
r.post(
  "/uploadimg",
  upload.fields([{ name: "file" }, { name: "files" }]),
  (req, res) => {
    let baseURL = `http://localhost:8088/upload/${req.files.file[0].filename}`;
    console.log(req.files.file);
    // console.log(req.body.Uid)
    let uid = req.body.Uid;
    // console.log(baseURL,baseURL2)
    let sql = "update user set user_urgent_car01 =?,user_urgent_car02 =?  ";
    if (req.files.file) {
      res.send({ err: 0, url: `${baseURL}` });
    } 
  }
);

// 11.获取用户订单信息
r.post("/usergetorder", (req, res, next) => {
  // console.log(req.body)
  let obj = req.body;
  let sql = "select * from car_order where ouser_id = ?";
  pool.query(sql, [obj.Uid], (err, data) => {
    if (err) {
      next(err);
      return;
    }
    if (data !== 0) {
      res.send({ code: 200, data: data });
    } else {
      res.send({ code: 201, msg: "暂无订单信息" });
    }
  });
});
// 2.token

module.exports = r;
